<?php
/*
 * class shm
 * Use for communication between php and php; in fact you can suppose this to be message pool
 * Create at: 11:18 2012/10/31
 * Author: leixun(lein_urg@163.com)
 * version 1 - 11:37 2012/10/31
 */

class shm{
	private $id;
	private $shm_id;
	private $auto_id = 0;
	private $read_id = 0;
	
	private $max_auto_id = 1000;
	/**
	 * @param $_id ID
	 * @param $block_size A single varible max size
	 * @param $block_count total block count
	 */
	public function shm($_id, $block_size=256, $block_count = 1000){
		$this->id = $_id;
		$this->shm_id = shm_attach ( $_id, $block_size * $block_count );
		$this->max_auto_id = $block_count;
		if ($id === false) {
			die(basename(__FILE__).'->'.__LINE__.': Unable to create the shared memory segment');
		}
	}
	
	/**
	 * @param $var varible to storage
	 * 
	 */
	public function attach($var)
	{
		$this->auto_id++;
		if( $this->auto_id > $this->max_auto_id )
		{
			$this->auto_id = 1;
		}

		if( shm_has_var( $this->shm_id , $this->auto_id ) )
		{
			return false;//no free space, all block are used
		}
		
		return shm_put_var( $this->shm_id , $this->auto_id , $var );//false , when no space
	}
	
	/**
	 * read one data, and remove it from shm
	 * 
	 */
	public function read()
	{
		$this->read_id++;
		if($this->read_id > $this->max_auto_id)
		{
			$this->read_id = 1;
		}

		if(!shm_has_var( $this->shm_id , $this->read_id ))
		{
			return false;
		}
		
		$var = shm_get_var( $this->shm_id , $this->read_id );
		shm_remove_var ( $this->shm_id , $this->read_id );
		
		return $var;
	}

	function __destruct()
	{
		shm_remove($this->shm_id); 
		shm_detach($this->shm_id);
	}	
}